package com.simonall.netty.resolver.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.simonall.netty.resolver.HttpParamResolver;

import cn.hutool.core.bean.BeanUtil;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

/**
 * 路径参数解析：action?a=val1&b=val2
 * 
 * @author simonall
 */
public class PathParamResolver implements HttpParamResolver {

	@Override
	public Map<String, List<String>> resolver(HttpRequest request) {
		return new QueryStringDecoder(request.uri()).parameters();
	}

	@Override
	public <T> T resolver(HttpRequest request, Class<T> clazz) {
		Map<String, Object> source = new HashMap<String, Object>();
		resolver(request).entrySet().forEach(entry -> {
			if (entry.getValue().size() == 1) {
				source.put(entry.getKey(), entry.getValue().get(0));
			} else {
				source.put(entry.getKey(), entry.getValue());
			}
		});
		return BeanUtil.toBeanIgnoreError(source, clazz);
	}
}
